package com.example.jinbi

import android.accessibilityservice.AccessibilityService
import android.accessibilityservice.GestureDescription
import android.graphics.Path
import android.graphics.Rect
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class MyAccessibilityService : AccessibilityService() {

    private var loading = false

    companion object {
        private const val TAG = "MyAccessibilityService"
    }


    override fun onAccessibilityEvent(event: AccessibilityEvent) {
        when (event.eventType) {
            AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED,
            AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED -> {
                if(!loading){
                    loading = true

                    CoroutineScope(Dispatchers.Main).launch {
                        delay(500)

                        printNodeTreeWithCoordinates(rootInActiveWindow)

                        val node = findNodesByTextStartsWith(rootInActiveWindow,"看视频再得").firstOrNull{it.isClickable}

                        if(node!=null){
                            val regex = Regex("\\d+")
                            regex.find(node.text)?.value?.let {
                                val num = it.toInt()
                                if(num>200){
                                    clickByNodeCenter(node,this@MyAccessibilityService)
                                }else{
                                    findNodesByTextEquals(rootInActiveWindow,"坚持退出").firstOrNull{it.isClickable}?.let { it2 ->
                                        clickByNodeCenter(it2,this@MyAccessibilityService)
                                    }
                                }
                            }

                        }else{
                            findNodesByTextEquals(rootInActiveWindow,"领取成功").firstOrNull{it.isClickable}?.let {
                                clickByNodeCenter(it,this@MyAccessibilityService)
                            }
                        }

                        loading = false
                    }

                }
            }
        }
    }

    override fun onInterrupt() {
        TODO("Not yet implemented")
    }

    // 节点点击（通过节点位置）
    fun clickByNodeCenter(node: AccessibilityNodeInfo, service: AccessibilityService) {
        val rect = Rect()
        node.getBoundsInScreen(rect)

        // 校验 bounds 合法性
        if (rect.left < 0 || rect.top < 0 || rect.right <= rect.left || rect.bottom <= rect.top) {
            Log.w("MyAccessibilityService", "点击跳过：坐标非法 $rect")
            return
        }

        val path = Path().apply {
            moveTo(rect.centerX().toFloat(), rect.centerY().toFloat())
        }

        val gesture = GestureDescription.Builder()
            .addStroke(GestureDescription.StrokeDescription(path, 0, 100))
            .build()

        service.dispatchGesture(gesture, null, null)
    }

    // 自定义滑动
    fun performScrollGesture(x1: Float, y1: Float, x2: Float, y2: Float) {
        val path = Path()
        path.moveTo(x1, y1)
        path.lineTo(x2, y2)

        val strokeDescription = GestureDescription.StrokeDescription(path, 0, 1000)
        val gestureDescription = GestureDescription.Builder()
            .addStroke(strokeDescription)
            .build()

        dispatchGesture(gestureDescription, null, null)
    }

    // 屏幕滚动
    fun scroll() {
        val displayMetrics = resources.displayMetrics
        val screenWidth = displayMetrics.widthPixels
        val screenHeight = displayMetrics.heightPixels

        val x = screenWidth / 2.0.toFloat()
        val y1 = screenHeight * 0.7.toFloat()
        val y2 = screenHeight * 0.3.toFloat()

        performScrollGesture(x, y1, x, y2)
    }

    // 打印节点树
    fun printNodeTreeWithCoordinates(
        node: AccessibilityNodeInfo?,
        indent: String = "",
        path: String = "",
        x: Int = 0,
        y: Int = 0,
        isLast: Boolean = true
    ) {
        if (node == null) return

        // 获取当前节点的信息
        val className = node.className?.toString() ?: "null"
        val viewId = node.viewIdResourceName ?: "null"
        val text = node.text?.toString() ?: "null"
        val desc = node.contentDescription?.toString() ?: "null"
        val clickable = node.isClickable
        val selected = node.isSelected
        val visibleToUser = node.isVisibleToUser

        // 构建并打印当前节点的信息，包括坐标 (x, y) 和连接符
        val coordinates = "($x,$y)"
        val connector = if (isLast) "└─" else "├─"
        val currentPath = if (path.isEmpty()) "$x" else "$path-$x"

        val txt = "$indent$connector $coordinates [${currentPath}] Class: $className, " +
                "ID: $viewId, Text: $text, desc: $desc, " +
                "clickable: $clickable, selected: $selected, visibleToUser: $visibleToUser"

        Log.d(TAG, txt)

        // 准备下一层级的前缀
        val newIndent = if (isLast) "$indent  " else "$indent│ "

        // 递归遍历子节点
        val childCount = node.childCount
        for (i in 0 until childCount) {
            val child = node.getChild(i)
            printNodeTreeWithCoordinates(
                child,
                newIndent,
                currentPath,
                i,
                y + 1,
                i == childCount - 1
            )
        }
    }

    fun findNodeByPath(rootNode: AccessibilityNodeInfo?, path: String): AccessibilityNodeInfo? {
        if (rootNode == null) return null
        if (path.isEmpty()) return rootNode

        val indices = path.split("-").mapNotNull { it.toIntOrNull() }
        var currentNode: AccessibilityNodeInfo? = rootNode

        for ((i, index) in indices.withIndex()) {
            if (i == 0) {
                if (index != 0) {
                    currentNode = null
                    break
                }
            } else {
                if (currentNode == null || index < 0 || index >= currentNode.childCount) {
                    return null
                }
                currentNode = currentNode.getChild(index)
            }
        }

        return currentNode
    }

    //查找所有text等于text的节点
    fun findNodesByTextEquals(
        root: AccessibilityNodeInfo?,
        text: String
    ): List<AccessibilityNodeInfo> {
        val result = mutableListOf<AccessibilityNodeInfo>()
        if (root == null) return result

        if ((root.text?.equals(text) == true) || (root.contentDescription?.equals(text) == true)) {
            result.add(root)
        }

        for (i in 0 until root.childCount) {
            val child = root.getChild(i)
            result.addAll(findNodesByTextEquals(child, text))
        }

        return result
    }

    //查找以text开头的节点
    fun findNodesByTextStartsWith(
        root: AccessibilityNodeInfo?,
        text: String
    ): List<AccessibilityNodeInfo> {
        val result = mutableListOf<AccessibilityNodeInfo>()
        if (root == null) return result

        if ((root.text?.startsWith(text) == true) || (root.contentDescription?.startsWith(text) == true)) {
            result.add(root)
        }

        for (i in 0 until root.childCount) {
            val child = root.getChild(i)
            result.addAll(findNodesByTextStartsWith(child, text))
        }

        return result
    }

    //查找以text结尾的节点
    fun findNodesByTextEndsWith(
        root: AccessibilityNodeInfo?,
        text: String
    ): List<AccessibilityNodeInfo> {
        val result = mutableListOf<AccessibilityNodeInfo>()
        if (root == null) return result

        if ((root.text?.endsWith(text) == true) || (root.contentDescription?.endsWith(text) == true)) {
            result.add(root)
        }

        for (i in 0 until root.childCount) {
            val child = root.getChild(i)
            result.addAll(findNodesByTextEndsWith(child, text))
        }

        return result
    }


}